package com.kh.pajx.sop.service.bal.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.kh.pajx.sop.base.BaseServiceImpl;
import com.kh.pajx.sop.dao.bal.IBalBuMgrDriveDao;
import com.kh.pajx.sop.dao.bal.IBalCashDriveDao;
import com.kh.pajx.sop.dao.bal.IBalCustMgrDriveDao;
import com.kh.pajx.sop.dao.bal.IBalMainBillDao;
import com.kh.pajx.sop.dao.bal.IBalTelfeeDriveDao;
import com.kh.pajx.sop.domain.bal.BalBuMgrDrive;
import com.kh.pajx.sop.domain.bal.BalCashDrive;
import com.kh.pajx.sop.domain.bal.BalCustMgrDrive;
import com.kh.pajx.sop.domain.bal.BalMainBill;
import com.kh.pajx.sop.domain.bal.BalTelfeeDrive;
import com.kh.pajx.sop.service.bal.IBalMainBillService;
import com.kh.pajx.sop.util.common.FormatDate;
import com.kh.pajx.sop.util.common.MathExtend;
import com.kh.pajx.sop.util.common.ValidatorUtils;
import com.kh.pajx.sop.util.page.QueryHelper;
import com.opensymphony.xwork2.ActionContext;

@Service
@Transactional
public class BalMainBillServiceImpl extends BaseServiceImpl<BalMainBill> implements IBalMainBillService {
	
	@Resource
	private IBalMainBillDao balMainBillDao;
	
	@Resource
	private IBalBuMgrDriveDao balBuMgrDriveDao;
	
	@Resource
	private IBalCustMgrDriveDao balCustMgrDriveDao;
	
	@Resource
	private IBalCashDriveDao balCashDriveDao;
	
	@Resource
	private IBalTelfeeDriveDao balTelfeeDriveDao;
	
	// ========================================================================================================
	
	@Override
	public void save(BalMainBill demo) {
		balMainBillDao.save(demo);
	}
	
	@Override
	public void update(BalMainBill demo) {
		balMainBillDao.update(demo);
	}
	
	// =====================================================================================================
	
	@Override
	public void findMyApp(String billCode,Integer balType, Integer billState,String userId, int pageNum, int numPerPage) throws Exception{
		new QueryHelper(BalMainBill.class,"bal")
		.addCondition("bal.appUserId=?", userId)
		//.addCondition(ValidatorUtils.validateFixedLengthNumber(billCode, 8, false),"bal.billCode=?", billCode)
		.addCondition(StringUtils.isNotBlank(billCode),"bal.billCode=?", billCode)
		.addCondition(ValidatorUtils.validateNumberRange(balType, 1, 6, false),"bal.balType=?", balType)
		.addCondition(ValidatorUtils.validateNumberRange(billState, 1, 3, false),"bal.billState=?", billState)
		.addOrderProperty("bal.billCode", false)
		.preparePageBean(balMainBillDao, pageNum, numPerPage);
	}
	
	@Override
	public void findMyCheck(String billCode,Integer balType,String userId, int pageNum, int numPerPage) throws Exception{
		new QueryHelper(BalMainBill.class,"bal")
		.addCondition("bal.chkUserId=?", userId)
		//.addCondition(ValidatorUtils.validateFixedLengthNumber(billCode, 8, false),"bal.billCode=?", billCode)
		.addCondition(StringUtils.isNotBlank(billCode),"bal.billCode=?", billCode)
		.addCondition(ValidatorUtils.validateNumberRange(balType, 1, 6, false),"bal.balType=?", balType)
		.addCondition("bal.billState=?", 2)
		.addOrderProperty("bal.billCode", false)
		.preparePageBean(balMainBillDao, pageNum, numPerPage);
	}
	
	@Override
	public void findMyMak(String billCode,Integer balType,String userId, int pageNum, int numPerPage) throws Exception{
		new QueryHelper(BalMainBill.class,"bal")
		.addCondition("bal.makUserId=?", userId)
		//.addCondition(ValidatorUtils.validateFixedLengthNumber(billCode, 8, false),"bal.billCode=?", billCode)
		.addCondition(StringUtils.isNotBlank(billCode),"bal.billCode=?", billCode)
		.addCondition(ValidatorUtils.validateNumberRange(balType, 1, 6, false),"bal.balType=?", balType)
		.addCondition("bal.billState=?", 3)
		.addOrderProperty("bal.billCode", false)
		.preparePageBean(balMainBillDao, pageNum, numPerPage);
	}
	
	@Override
	public void findCheck(String billCode, Integer balType, int pageNum, int numPerPage) throws Exception {
		new QueryHelper(BalMainBill.class,"bal")
		.addCondition("bal.billState=?", 1)
		.addCondition(StringUtils.isNotBlank(billCode),"bal.billCode=?", billCode)
		.addCondition(ValidatorUtils.validateFixedLengthNumber(balType, 1, false),"bal.balType=?", balType)
		.addOrderProperty("bal.billCode", false)
		.preparePageBean(balMainBillDao, pageNum, numPerPage);
	}
	
	@Override
	public void findMak(String billCode, Integer balType, int pageNum, int numPerPage) throws Exception {
		new QueryHelper(BalMainBill.class,"bal")
		.addCondition("bal.billState=?", 2)
		.addCondition(StringUtils.isNotBlank(billCode),"bal.billCode=?", billCode)
		.addCondition(ValidatorUtils.validateFixedLengthNumber(balType, 1, false),"bal.balType=?", balType)
		.addOrderProperty("bal.billCode", false)
		.preparePageBean(balMainBillDao, pageNum, numPerPage);
	}
	
	@Override
	public void findTelfeeDetail(String billCode, int pageNum, int numPerPage) throws Exception{
		new QueryHelper(BalTelfeeDrive.class,"bal")
		.addCondition("bal.billCode=?", billCode)
		.addOrderProperty("bal.ywEndDate", false)
		.addOrderProperty("bal.saleDeptId", true)
		.addOrderProperty("bal.sclName", true)
		.preparePageBean(balTelfeeDriveDao, pageNum, numPerPage);
	}
	
	@Override
	public void findCashDetail(String billCode, int pageNum, int numPerPage) throws Exception{
		new QueryHelper(BalCashDrive.class, "bal")
		.addCondition("bal.billCode=?", billCode)
		.addOrderProperty("bal.ywEndDate", false)
		.addOrderProperty("bal.saleDeptId", true)
		.addOrderProperty("bal.sclName", true)
		.preparePageBean(balCashDriveDao, pageNum, numPerPage);
	}
	
	@Override
	public void findCustMgrDetail(String billCode, int pageNum, int numPerPage) throws Exception{
		new QueryHelper(BalCustMgrDrive.class, "bal")
		.addCondition("bal.billCode=?", billCode)
		.addOrderProperty("bal.ywEndDate", false)
		.addOrderProperty("bal.saleDeptId", true)
		.addOrderProperty("bal.sclName", true)
		.preparePageBean(balCustMgrDriveDao, pageNum, numPerPage);
	}
	
	@Override
	public void findBuMgrDetail(String billCode, int pageNum, int numPerPage) throws Exception{
		new QueryHelper(BalBuMgrDrive.class, "bal")
		.addCondition("bal.billCode=?", billCode)
		.addOrderProperty("bal.ywEndDate", false)
		.addOrderProperty("bal.saleDeptId", true)
		.addOrderProperty("bal.areaName", true)
		.preparePageBean(balBuMgrDriveDao, pageNum, numPerPage);
	}
	
	
	// =====================================================================================================
	 
	@Override
	public void appTelFee(String balIds,String pageTotalFee,String userId, String deptCode) throws Exception{
		String[] balIdArray = balIds.split(",");
		double totalFee = 0.0;
		for(String balId : balIdArray){
			BalTelfeeDrive telFee = balTelfeeDriveDao.getById(balId);
			if(null != telFee.getBalFee()){
				totalFee = MathExtend.add(totalFee, balTelfeeDriveDao.getById(balId).getBalFee());
			}
		}
		
		if(!MathExtend.formatDouble(pageTotalFee).equals(MathExtend.formatDouble(totalFee))){
			System.out.println(MathExtend.formatDouble(pageTotalFee) +"============>" +MathExtend.formatDouble(totalFee));
			throw new Exception("结算总金额不允许篡改！");
		}
		BalMainBill bill = new BalMainBill();
		bill.setBillCode(getNextBillCode(deptCode));  
		bill.setBillState(1);
		bill.setBalType(3);
		bill.setAppUserId(userId);
		bill.setAppDate(FormatDate.dateTimeDetail());
		bill.setAppFee(totalFee);
		bill.setPntFlag(0);
		balMainBillDao.save(bill);
		for(String balId : balIdArray){
			BalTelfeeDrive telFee = balTelfeeDriveDao.getById(balId);
			telFee.setBillState(1);
			telFee.setBillCode(bill.getBillCode());
			balTelfeeDriveDao.update(telFee);
		}
	}
	
	@Override
	public void appCash(String balIds,String pageTotalFee,String userId, String deptCode) throws Exception{
		String[] balIdArray = balIds.split(",");
		double totalFee = 0.0;
		for(String balId : balIdArray){
			BalCashDrive cashDrive = balCashDriveDao.getById(balId);
			if(null != cashDrive.getBalFee()){
				totalFee = MathExtend.add(totalFee, balCashDriveDao.getById(balId).getBalFee());
			}
		}
		
		if(!MathExtend.formatDouble(pageTotalFee).equals(MathExtend.formatDouble(totalFee))){
			System.out.println(MathExtend.formatDouble(pageTotalFee) +"============>" +MathExtend.formatDouble(totalFee));
			throw new Exception("结算总金额不允许篡改！");
		}
		BalMainBill bill = new BalMainBill();
		bill.setBillCode(getNextBillCode(deptCode));  
		bill.setBillState(1);
		bill.setBalType(4);
		bill.setAppUserId(userId);
		bill.setAppDate(FormatDate.dateTimeDetail());
		bill.setAppFee(totalFee);
		bill.setPntFlag(0);
		balMainBillDao.save(bill);
		for(String balId : balIdArray){
			BalCashDrive cashDrive = balCashDriveDao.getById(balId);
			cashDrive.setBillState(1);
			cashDrive.setBillCode(bill.getBillCode());
			balCashDriveDao.update(cashDrive);
		}
	}
	
	@Override
	public void appCustMgr(String balIds,String pageTotalFee,String userId, String deptCode) throws Exception{
		String[] balIdArray = balIds.split(",");
		double totalFee = 0.0;
		for(String balId : balIdArray){
			BalCustMgrDrive custMgr = balCustMgrDriveDao.getById(balId);
			if(null != custMgr.getBalFee()){
				totalFee = MathExtend.add(totalFee, balCustMgrDriveDao.getById(balId).getBalFee());
			}
		}
		
		if(!MathExtend.formatDouble(pageTotalFee).equals(MathExtend.formatDouble(totalFee))){
			System.out.println(MathExtend.formatDouble(pageTotalFee) +"============>" +MathExtend.formatDouble(totalFee));
			throw new Exception("结算总金额不允许篡改！");
		}
		BalMainBill bill = new BalMainBill();
		bill.setBillCode(getNextBillCode(deptCode));  
		bill.setBillState(1);
		bill.setBalType(5);
		bill.setAppUserId(userId);
		bill.setAppDate(FormatDate.dateTimeDetail());
		bill.setAppFee(totalFee);
		bill.setPntFlag(0);
		balMainBillDao.save(bill);
		for(String balId : balIdArray){
			BalCustMgrDrive custMgr = balCustMgrDriveDao.getById(balId);
			custMgr.setBillState(1);
			custMgr.setBillCode(bill.getBillCode());
			balCustMgrDriveDao.update(custMgr);
		}
	}
	
	@Override
	public void appBuMgr(String balIds,String pageTotalFee,String userId, String deptCode) throws Exception{
		String[] balIdArray = balIds.split(",");
		double totalFee = 0.0;
		for(String balId : balIdArray){
			BalBuMgrDrive balBuMgr = balBuMgrDriveDao.getById(balId);
			if(null!=balBuMgr.getBalFee()){
				totalFee = MathExtend.add(totalFee, balBuMgrDriveDao.getById(balId).getBalFee());
			}
		}
		
		if(!MathExtend.formatDouble(pageTotalFee).equals(MathExtend.formatDouble(totalFee))){
			System.out.println(MathExtend.formatDouble(pageTotalFee) +"============>" +MathExtend.formatDouble(totalFee));
			throw new Exception("结算总金额不允许篡改！");
		}
		BalMainBill bill = new BalMainBill();
		bill.setBillCode(getNextBillCode(deptCode));  
		bill.setBillState(1);
		bill.setBalType(6);
		bill.setAppUserId(userId);
		bill.setAppDate(FormatDate.dateTimeDetail());
		bill.setAppFee(totalFee);
		bill.setPntFlag(0);
		balMainBillDao.save(bill);
		for(String balId : balIdArray){
			BalBuMgrDrive balBuMgr = balBuMgrDriveDao.getById(balId);
			balBuMgr.setBillState(1);
			balBuMgr.setBillCode(bill.getBillCode());
			balBuMgrDriveDao.update(balBuMgr);
		}
	}
	
	// =========================================================================================================
	
	
	
	
	private String getNextBillCode(String deptCode) throws Exception{
		Integer maxBillCode = balMainBillDao.getMaxBillCode(deptCode);
		if(maxBillCode!=null && maxBillCode>0){
			return (maxBillCode+1)+"";
		}else{
			return deptCode+"0001";
		}
	}
	
	
	@Override
	public void cancelApp(String uuid) throws Exception {
		BalMainBill mainBill = getById(uuid);
		if(mainBill == null){
			throw new Exception("无对应结算单据信息！");
		}
		if(mainBill.getBillState()!=1){
			throw new Exception("该单据不允许撤销！");
		}else{
			// 重置单据明细
			if(mainBill.getBalType()==3){
				// 重置结算信息
				List<BalTelfeeDrive> telFeeList = balTelfeeDriveDao.findList(mainBill.getBillCode(), 1);
				for(BalTelfeeDrive telFee : telFeeList){
					telFee.setBillState(0);
					telFee.setBillCode("");
					//telFee.setPayFee(telFee.getBalFee());
					//telFee.setSpecDeclare("按照实际统计数据支付");
					balTelfeeDriveDao.update(telFee);
				}
				// 删除单据
				delete(uuid);
			}else if(mainBill.getBalType()==4){
				// 重置结算信息
				List<BalCashDrive> cashList = balCashDriveDao.findList(mainBill.getBillCode(), 1);
				for(BalCashDrive cash : cashList){
					cash.setBillState(0);
					cash.setBillCode("");
					//cash.setPayFee(cash.getBalFee());
					//cash.setSpecDeclare("按照实际统计数据支付");
					balCashDriveDao.update(cash);
				}
				// 删除单据
				delete(uuid);
			}else if(mainBill.getBalType()==5){
				// 重置结算信息
				List<BalCustMgrDrive> custMgrList = balCustMgrDriveDao.findList(mainBill.getBillCode(),1);
				for(BalCustMgrDrive custMgr : custMgrList){
					custMgr.setBillState(0);
					custMgr.setBillCode("");
					//custMgr.setPayFee(custMgr.getBalFee());
					//custMgr.setSpecDeclare("按照实际统计数据支付");
					balCustMgrDriveDao.update(custMgr);
				}
				// 删除单据
				delete(uuid);
			}else if(mainBill.getBalType()==6){
				// 重置结算信息
				List<BalBuMgrDrive> buMgrList = balBuMgrDriveDao.findList(mainBill.getBillCode(), 1);
				for (BalBuMgrDrive buMgr : buMgrList) {
					buMgr.setBillState(0);
					buMgr.setBillCode("");
					//buMgr.setPayFee(buMgr.getBalFee());
					//buMgr.setSpecDeclare("按照实际统计数据支付");
					balBuMgrDriveDao.update(buMgr);
				}
				
				// 删除单据
				delete(uuid);
			}
		}
	}
	
	
	@Override
	public void cancelCheck(String uuid) throws Exception {
		BalMainBill mainBill = getById(uuid);
		if(mainBill == null){
			throw new Exception("无对应结算单据信息！");
		}
		if(mainBill.getBillState()!=2){
			throw new Exception("该单据不允许撤销！");
		}else{
			// 重置单据明细
			if(mainBill.getBalType()==3){
				// 重置结算信息
				List<BalTelfeeDrive> telFeeList = balTelfeeDriveDao.findList(mainBill.getBillCode(), 2);
				for(BalTelfeeDrive telFee : telFeeList){
					telFee.setBillState(1);
					telFee.setPayFee(telFee.getBalFee());
					telFee.setSpecDeclare("按照实际统计数据支付");
					balTelfeeDriveDao.update(telFee);
				}
				
				// 重置主单据
				mainBill.setChkDate("");
				mainBill.setChkUserId("");
				mainBill.setChkFee(null);
				mainBill.setBillState(1);
				update(mainBill);
				
				
			}else if(mainBill.getBalType()==4){
				// 重置结算信息
				List<BalCashDrive> cashList = balCashDriveDao.findList(mainBill.getBillCode(), 2);
				for(BalCashDrive cash : cashList){
					cash.setBillState(1);
					cash.setPayFee(cash.getBalFee());
					cash.setSpecDeclare("按照实际统计数据支付");
					balCashDriveDao.update(cash);
				}
				
				// 重置主单据
				mainBill.setChkDate("");
				mainBill.setChkUserId("");
				mainBill.setChkFee(null);
				mainBill.setBillState(1);
				update(mainBill);
			}else if(mainBill.getBalType()==5){
				// 重置结算信息
				List<BalCustMgrDrive> custMgrList = balCustMgrDriveDao.findList(mainBill.getBillCode(),2);
				for(BalCustMgrDrive custMgr : custMgrList){
					custMgr.setBillState(1);
					custMgr.setPayFee(custMgr.getBalFee());
					custMgr.setSpecDeclare("按照实际统计数据支付");
					balCustMgrDriveDao.update(custMgr);
				}
				
				// 重置主单据
				mainBill.setChkDate("");
				mainBill.setChkUserId("");
				mainBill.setChkFee(null);
				mainBill.setBillState(1);
				update(mainBill);
			}else if(mainBill.getBalType()==6){
				// 重置结算信息
				List<BalBuMgrDrive> buMgrList = balBuMgrDriveDao.findList(mainBill.getBillCode(), 2);
				for (BalBuMgrDrive buMgr : buMgrList) {
					buMgr.setBillState(1);
					buMgr.setPayFee(buMgr.getBalFee());
					buMgr.setSpecDeclare("按照实际统计数据支付");
					balBuMgrDriveDao.update(buMgr);
				}
				
				// 重置主单据
				mainBill.setChkDate("");
				mainBill.setChkUserId("");
				mainBill.setChkFee(null);
				mainBill.setBillState(1);
				update(mainBill);
			}
		}
	}
	
	
	@Override
	public void checkApp(BalMainBill model,String userId,String[] uuidArray,String[] payFeeArray,String[] remarkArray) throws Exception {
		
		// ==>1. 组织元数据
		if(!(uuidArray.length==payFeeArray.length && uuidArray.length==remarkArray.length)){
			throw new Exception("传入参数不全，系统无法匹配处理！");
		}
		Map<String,String> payFeeMap = new HashMap<String, String>();
		Map<String,String> remarkMap = new HashMap<String, String>();
		for (int i = 0; i < uuidArray.length; i++) {
			if(!ValidatorUtils.validateUUID(uuidArray[i], false)){
				throw new Exception("非法参数提交！");
			}
			payFeeMap.put(uuidArray[i], payFeeArray[i]);
			remarkMap.put(uuidArray[i], remarkArray[i]);
		}
		
		double totalFee = 0.0;
		for (String fee :payFeeArray) {
			if(StringUtils.isNotBlank(fee)){
				totalFee = MathExtend.add(totalFee, Double.valueOf(fee));
			}
		}
		if(!(totalFee+"").equals(model.getChkFee()+"")){
			throw new Exception("总金额已被篡改！");
		}
		
		BalMainBill bill = balMainBillDao.getById(model.getUuid());
		if(null == bill){
			throw new Exception("暂无对应结算单据信息！");
		}
		
		// ==>2. 更新单据明细
		if(bill.getBalType()==6){
			List<BalBuMgrDrive> buMgrList = balBuMgrDriveDao.findList(bill.getBillCode(), 1);
			for(BalBuMgrDrive buMgr : buMgrList){
				if(StringUtils.isNotBlank(payFeeMap.get(buMgr.getUuid()))){
					buMgr.setPayFee(Double.valueOf(payFeeMap.get(buMgr.getUuid())));
				}
				buMgr.setSpecDeclare(remarkMap.get(buMgr.getUuid()));
				buMgr.setBillState(2);
				balBuMgrDriveDao.update(buMgr);
			}
		} else if(bill.getBalType()==5){
			List<BalCustMgrDrive> custList = balCustMgrDriveDao.findList(bill.getBillCode(), 1);
			for(BalCustMgrDrive custMgr : custList){
				if(StringUtils.isNotBlank(payFeeMap.get(custMgr.getUuid()))){
					custMgr.setPayFee(Double.valueOf(payFeeMap.get(custMgr.getUuid())));
				}
				custMgr.setSpecDeclare(remarkMap.get(custMgr.getUuid()));
				custMgr.setBillState(2);
				balCustMgrDriveDao.update(custMgr);
			}
		} else if(bill.getBalType()==4){
			List<BalCashDrive> cashList = balCashDriveDao.findList(bill.getBillCode(), 1);
			for(BalCashDrive cash : cashList){
				if(StringUtils.isNotBlank(payFeeMap.get(cash.getUuid()))){
					cash.setPayFee(Double.valueOf(payFeeMap.get(cash.getUuid())));
				}
				cash.setSpecDeclare(remarkMap.get(cash.getUuid()));
				cash.setBillState(2);
				balCashDriveDao.update(cash);
			}
		} else if(bill.getBalType()==3){
			List<BalTelfeeDrive> telfeeList = balTelfeeDriveDao.findList(bill.getBillCode(), 1);
			for(BalTelfeeDrive telfee : telfeeList){
				if(StringUtils.isNotBlank(payFeeMap.get(telfee.getUuid()))){
					telfee.setPayFee(Double.valueOf(payFeeMap.get(telfee.getUuid())));
				}
				telfee.setSpecDeclare(remarkMap.get(telfee.getUuid()));
				telfee.setBillState(2);
				balTelfeeDriveDao.update(telfee);
			}
		}
		
		// ==>3. 更新主单据
		bill.setChkFee(totalFee);
		bill.setChkUserId(userId);
		bill.setChkDate(FormatDate.dateTimeDetail());
		bill.setBillState(2);
		bill.setSpecDeclare(model.getSpecDeclare());
		update(bill);
	}
	
	@Override
	public BalMainBill getById(String id) {
		return balMainBillDao.getById(id);
	}
	
	@Override
	public void delete(String uuid) {
		balMainBillDao.delete(uuid);
	}
	
	@Override
	public BalMainBill getByCode(String billCode) throws Exception {
		return balMainBillDao.getByCode(billCode);
	}
	
	
	@Override
	public void makApp(BalMainBill model,String userId) throws Exception {
		
		// ==>1. 校验单据
		BalMainBill bill = balMainBillDao.getById(model.getUuid());
		if(null == bill){
			throw new Exception("暂无对应结算单据信息！");
		}
		
		if(bill.getBillState()!=2){
			throw new Exception("该单据已被撤销或删除，无法进行签批操作！");
		}
		
		if(bill.getPntFlag()!=1){
			throw new Exception("该单据尚未打印，无法进行签批操作！");
		}
		
		// ==>2. 更新单据明细
		if(bill.getBalType()==6){
			List<BalBuMgrDrive> buMgrList = balBuMgrDriveDao.findList(bill.getBillCode(), 2);
			for(BalBuMgrDrive buMgr : buMgrList){
				buMgr.setBillState(3);
				balBuMgrDriveDao.update(buMgr);
			}
		} else if(bill.getBalType()==5){
			List<BalCustMgrDrive> custList = balCustMgrDriveDao.findList(bill.getBillCode(), 2);
			for(BalCustMgrDrive custMgr : custList){
				custMgr.setBillState(3);
				balCustMgrDriveDao.update(custMgr);
			}
		} else if(bill.getBalType()==4){
			List<BalCashDrive> cashList = balCashDriveDao.findList(bill.getBillCode(), 2);
			for(BalCashDrive cash : cashList){
				cash.setBillState(3);
				balCashDriveDao.update(cash);
			}
		} else if(bill.getBalType()==3){
			List<BalTelfeeDrive> telfeeList = balTelfeeDriveDao.findList(bill.getBillCode(), 2);
			for(BalTelfeeDrive telfee : telfeeList){
				telfee.setBillState(3);
				balTelfeeDriveDao.update(telfee);
			}
		}
		
		// ==>3. 更新主单据
		bill.setBillState(3);
		bill.setMakDate(FormatDate.dateTimeDetail());
		bill.setMakUserId(userId);
		update(bill);
	}
	
	
	@Override
	public void statistics(String deptCode, String areaCode, String startDate, String endDate) throws Exception{
		
		System.out.println("======>进入结算统计业务处理");
		
		System.out.println("======>1.校验输入参数");
		// 输入参数校验  签批日期、大区、地区
		if(StringUtils.isBlank(startDate) && StringUtils.isBlank(endDate)){
			throw new Exception("请至少选择一个日期！");
		}
		
		if(StringUtils.isNotBlank(startDate)){
			startDate = startDate.replace("-", "");
		}else{
			startDate = "20150101";
		}
		
		if(StringUtils.isNotBlank(endDate)){
			endDate = endDate.replace("-", "");
			if(!ValidatorUtils.validateFixedLengthNumber(endDate, 8, true)){
				throw new Exception("检索条件[签批日期]检测到非法参数请求！");
			}
			endDate = FormatDate.daysAfterOneDate(endDate,1);
		}else{
			endDate = FormatDate.daysAfterOneDate(FormatDate.dateChange(),1);
		}
		
		if(!ValidatorUtils.validateFixedLengthNumber(startDate, 8, true)){
			throw new Exception("检索条件[签批日期]检测到非法参数请求！");
		}
		
	
		
		if(!ValidatorUtils.validateFixedLengthNumber(deptCode, 4, true)){
			throw new Exception("检索条件[所属大区]检测到非法参数请求！");
		}
		
		if(!ValidatorUtils.validateFixedLengthNumber(areaCode, 4, true)){
			throw new Exception("检索条件[地区]检测到非法参数请求！");
		}
		
		if(!ValidatorUtils.validateFixedLengthNumber(areaCode, 4, true)){
			throw new Exception("检索条件[地区]检测到非法参数请求！");
		}
		
		if(!ValidatorUtils.validateFixedLengthNumber(areaCode, 4, true)){
			throw new Exception("检索条件[地区]检测到非法参数请求！");
		}
				
		System.out.println("======>2.获取结算单据信息");
		// 1.根据签批时间范围查找主单据
		List<BalMainBill> balMainList = balMainBillDao.findByMakDate(startDate, endDate);
		System.out.println("======>共计"+balMainList.size()+"条");
		
		List<String> bumgrBills = new ArrayList<String>();
		List<String> custMgrBills = new ArrayList<String>();
		List<String> cashBills = new ArrayList<String>();
		List<String> telfeeBills = new ArrayList<String>();
		
		System.out.println("======>3.结算单据类型分析");
		for (BalMainBill bill : balMainList) {
			if(bill.getBalType()==6){
				bumgrBills.add(bill.getBillCode());
			}else if(bill.getBalType()==5){
				custMgrBills.add(bill.getBillCode());
			}else if(bill.getBalType()==4){
				cashBills.add(bill.getBillCode());
			}else if(bill.getBalType()==3){
				telfeeBills.add(bill.getBillCode());
			}
		}
		System.out.println("======>话费返还：" + telfeeBills.size());
		System.out.println("======>现金返还：" + cashBills.size());
		System.out.println("======>客户经理：" + custMgrBills.size());
		System.out.println("======>行业经理：" + bumgrBills.size());
		
		// 2.根据主单据编号查找子对应子单据信息
		List<BalBuMgrDrive> buMgrList = new ArrayList<BalBuMgrDrive>(); 
		List<BalCustMgrDrive> custList = new ArrayList<BalCustMgrDrive>();
		List<BalCashDrive> cashList = new ArrayList<BalCashDrive>();
		List<BalTelfeeDrive> telfeeList = new ArrayList<BalTelfeeDrive>();
		
		System.out.println("======>4.存储结果数据");
		// 3.根据子单据组装结果数据
		if(areaCode.equals("0000")){
			// =======================全部地区=================================
			if(deptCode.equals("0000")){
				// 全部大区
				// ==1.行业经理
				if(bumgrBills.size() > 0)
					buMgrList = balBuMgrDriveDao.findByBillCodeList(bumgrBills);
				
				// ==2.客户经理
				if(custMgrBills.size() > 0)
					custList = balCustMgrDriveDao.findByBillCodeList(custMgrBills);
				
				// ==3.现金返还
				if(cashBills.size() > 0)
					cashList = balCashDriveDao.findByBillCodeList(cashBills);
				
				// ==4.话费返还
				if(telfeeBills.size() > 0)
					telfeeList = balTelfeeDriveDao.findByBillCodeList(telfeeBills);
				
			}else{
				// 指定大区
				// ==1.行业经理
				if(bumgrBills.size() > 0)
					buMgrList = balBuMgrDriveDao.findByBillCodeList(bumgrBills, null , deptCode);
				
				// ==2.客户经理
				if(custMgrBills.size() > 0)
					custList = balCustMgrDriveDao.findByBillCodeList(custMgrBills, null, deptCode);
				
				// ==3.现金返还
				if(cashBills.size() > 0)
					cashList = balCashDriveDao.findByBillCodeList(cashBills, null, deptCode);
				
				// ==4.话费返还
				if(telfeeBills.size() > 0)
					telfeeList = balTelfeeDriveDao.findByBillCodeList(telfeeBills, null, deptCode);
			}
		}else{
			// =======================指定地区=================================
			
			// ==1.行业经理
			if(bumgrBills.size() > 0)
				buMgrList = balBuMgrDriveDao.findByBillCodeList(bumgrBills, areaCode);
			
			// ==2.客户经理
			if(custMgrBills.size() > 0)
				custList = balCustMgrDriveDao.findByBillCodeList(custMgrBills, areaCode);
			
			// ==3.现金返还
			if(cashBills.size() > 0)
				cashList = balCashDriveDao.findByBillCodeList(cashBills, areaCode);
			
			// ==4.话费返还
			if(telfeeBills.size() > 0)
				telfeeList = balTelfeeDriveDao.findByBillCodeList(telfeeBills, areaCode);
		}
		
		System.out.println("======>话费返还：" + telfeeList.size());
		System.out.println("======>现金返还：" + cashList.size());
		System.out.println("======>客户经理：" + custList.size());
		System.out.println("======>行业经理：" + buMgrList.size());
		
		double totalFee = 0.0;
		double bumgrTotalFee = 0.0;
		double custTotalFee = 0.0;
		double cashTotalFee = 0.0;
		double telfeeTotalFee = 0.0;
		
		for (BalBuMgrDrive bumgr : buMgrList) {
			bumgrTotalFee = MathExtend.add(bumgrTotalFee, bumgr.getPayFee());
		}
		
		for (BalCustMgrDrive cust : custList) {
			custTotalFee = MathExtend.add(custTotalFee, cust.getPayFee());
		}
		
		for (BalCashDrive cash : cashList) {
			cashTotalFee = MathExtend.add(cashTotalFee, cash.getPayFee());
		}
		
		for (BalTelfeeDrive telfee : telfeeList) {
			telfeeTotalFee = MathExtend.add(telfeeTotalFee, telfee.getPayFee());
		}
		
		ActionContext.getContext().put("buMgrList", buMgrList);
		ActionContext.getContext().put("custList", custList);
		ActionContext.getContext().put("cashList", cashList);
		ActionContext.getContext().put("telfeeList", telfeeList);
		
		ActionContext.getContext().put("bumgrTotalFee", bumgrTotalFee);
		ActionContext.getContext().put("custTotalFee", custTotalFee);
		ActionContext.getContext().put("cashTotalFee", cashTotalFee);
		ActionContext.getContext().put("telfeeTotalFee", telfeeTotalFee);
		
		totalFee = MathExtend.add(totalFee, bumgrTotalFee);
		totalFee = MathExtend.add(totalFee, custTotalFee);
		totalFee = MathExtend.add(totalFee, cashTotalFee);
		totalFee = MathExtend.add(totalFee, telfeeTotalFee);
		ActionContext.getContext().put("totalFee", totalFee);
	}
}
